package com.sfy.mallchat.common.user.service.impl;

import com.sfy.mallchat.common.common.constant.RedisKey;
import com.sfy.mallchat.common.user.service.LoginService;
import com.sfy.mallchat.common.common.utils.JwtUtils;
import com.sfy.mallchat.common.common.utils.RedisUtils;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    public static final int TOKEN_EXPIRE_DAYS = 3;
    public static final int TOKEN_RENEW_DAYS = 1;
    @Autowired
    private JwtUtils jwtUtils;

    //异步刷新
    ThreadPoolExecutor executor;

    @Override
    @Async
    public void renewalTokenIfNecessary(String token) {
        Long uid = getValidUid(token);
        String userTokenKey = getUserTokenKey(uid);
        Long expire = RedisUtils.getExpire(userTokenKey, TimeUnit.DAYS);
        if(expire == -2){
            return;
        }
        if(expire < TOKEN_RENEW_DAYS){
            RedisUtils.set(userTokenKey,token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        }
    }

    @Override
    public String login(Long uid) {
        String token = jwtUtils.createToken(uid);
        RedisUtils.set(getUserTokenKey(uid),token, TOKEN_EXPIRE_DAYS, TimeUnit.DAYS);
        return token;
    }

    @Override
    public Long getValidUid(String token) {
        Long uid = JwtUtils.getUidOrNull(token);
        if(Objects.isNull(uid)){
            return null;
        }
        String oldToken = RedisUtils.get(getUserTokenKey(uid));
        if(StringUtil.isBlank(oldToken)){
            return null;
        }
        return Objects.equals(oldToken,token)?uid:null;
    }

    /**
     * 辅助方法
     * @param uid
     * @return
     */
    private String getUserTokenKey(Long uid){
        return RedisKey.getKey(RedisKey.USER_TOKEN_STRING,uid);
    }
}
